package top.saybook.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import top.saybook.CacheKey;
import top.saybook.mapper.ChapterMapper;
import top.saybook.pojo.Chapter;
import top.saybook.service.ChapterService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    // 根据书籍ID删除数据库和redis中的所有章节
    public void delete(Integer bookId) {
        Example example = new Example(Chapter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bookId",bookId);
        chapterMapper.deleteByExample(example);
        redisTemplate.boundHashOps(CacheKey.CHAPTER).delete(bookId);//删除所有章节
        redisTemplate.delete(bookId); //删除所有章节内容
    }

    // 章节map集合转换成chapter集合
    private List<Chapter> mapChapterListToChapterList(List<Map> mapChapterList,Integer bookId) {
        List<Chapter> chapterList = new ArrayList<>();
        for (Map map : mapChapterList) {
            Chapter chapter = new Chapter();
            chapter.setBookId(bookId);
            chapter.setChapter((String) map.get("chapterName"));
            chapter.setLinkUrl((String) map.get("linkUrl"));
            chapterList.add(chapter);
        }
        return chapterList;
    }


}
